package com.moonciki.multids.multi;

import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.core.annotation.Order;

import java.sql.SQLException;

/**
 * 切换数据源Advice
 */
//@Aspect
@Order(-10)//保证该AOP在@Transactional之前执行
//@Component
public class DynamicDataSourceAspect {

    protected Object changeDataSource(ProceedingJoinPoint joinPoint, String dbName) throws Throwable {
        Object returnObj = null;

        String dataSourceKey = DynamicDataSourceContextHolder.getDataSourceKey(dbName);

        if (!DynamicDataSourceContextHolder.containsDataSource(dataSourceKey)) {
            throw new SQLException("data_source_anme not exists!");
        } else {
            try {
                Object target = joinPoint.getTarget();

                DynamicDataSourceContextHolder.setDataSourceType(dataSourceKey);
                returnObj = joinPoint.proceed();
            } finally {
                DynamicDataSourceContextHolder.clearDataSourceType();
            }
        }
        return returnObj;
    }

    /**
    @Around(base_point)
    public Object businessDataSource(ProceedingJoinPoint joinPoint) throws Throwable {
        Object returnObj = changeDataSource(joinPoint, "business");
        return returnObj;
    }
    */

}
